//
//  XMExchangeViewController.m
//  gpos_app
//
//  Created by apple on 2018/10/9.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "XMExchangeViewController.h"
#import "Masonry.h"
#import "GPosAPI.h"
#import "EBCountDownButton.h"
#import "SVProgressHUD.h"
#import "WKProgressHUD.h"
#import "XMRegisterViewController.h"
#import "XMHomeViewController.h"


#define NUM @"0123456789."
#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz."
#define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789."


@interface XMExchangeViewController ()<UITextFieldDelegate>
@property (nonatomic,strong)UIView * oneView;
@property (nonatomic,strong)UIView * twoView;
@property (nonatomic,strong)UIView * threeView;
@property (nonatomic,strong)UITextField * shuliangTextField;
@property (nonatomic,strong)UIButton * yanjingButton;
@property (nonatomic,strong)UITextField * jymimaTextField;
@property (nonatomic,strong)EBCountDownButton * yanzhengmaButton;
@property (nonatomic,strong)UITextField * yanzhengmaTextField;
@property (nonatomic,strong)UIButton * querenButton;
@property (nonatomic,strong)WKProgressHUD * hud;
@property (nonatomic,strong)UILabel * sjNbrtextlabel;

@end

@implementation XMExchangeViewController

//改变状态栏
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:244/255.0f green:244/255.0f blue:244/255.0f alpha:1];;
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.backgroundColor=[UIColor whiteColor];
    self.navigationController.navigationBar.tintColor=[UIColor blackColor];
    self.title = @"转入交易所";
    [self UIloadView];
    
    
}

- (void)UIloadView{
    self.oneView = [[UIView alloc] init];
    self.oneView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.oneView];
    [self.oneView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(kNavbarHeight + 10);
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.height.equalTo(@50);
    }];
    
    self.twoView = [[UIView alloc] init];
    self.twoView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.twoView];
    [self.twoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.oneView.mas_bottom).with.offset(2);
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.height.equalTo(@50);
    }];
    
    self.threeView = [[UIView alloc] init];
    self.threeView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.threeView];
    [self.threeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.twoView.mas_bottom).with.offset(52);
        make.left.equalTo(self.view).with.offset(0);
        make.right.equalTo(self.view).with.offset(0);
        make.height.equalTo(@50);
    }];
    
    UILabel * shuliangLabel = [[UILabel alloc] init];
    shuliangLabel.text = @"数量";
    shuliangLabel.font = [UIFont systemFontOfSize:14];
    [self.oneView addSubview:shuliangLabel];
    [shuliangLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.oneView);
        make.left.equalTo(self.oneView).with.offset(15);
        make.width.equalTo(@60);
    }];
    
    UILabel * GPOSLabel = [[UILabel alloc] init];
    GPOSLabel.text = @"GPOS";
    GPOSLabel.font = [UIFont systemFontOfSize:14];
    [self.oneView addSubview:GPOSLabel];
    [GPOSLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.oneView);
        make.width.equalTo(@40);
        make.right.equalTo(self.oneView).with.offset(-15);
    }];
    
    self.shuliangTextField = [[UITextField alloc] init];
    self.shuliangTextField.keyboardType=UIKeyboardTypeDecimalPad;
    [self.oneView addSubview:self.shuliangTextField];
    [self.shuliangTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.oneView);
        make.left.equalTo(shuliangLabel.mas_right).with.offset(15);
        make.right.equalTo(GPOSLabel.mas_left).with.offset(-15);
        
    }];
    self.shuliangTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.shuliangTextField.placeholder =@"请输入GPOS数量";
    self.shuliangTextField.font = [UIFont systemFontOfSize:14.f];
    self.shuliangTextField.delegate = self;
    
    
    UILabel * jymiomaLabel = [[UILabel alloc] init];
    jymiomaLabel.text = @"交易密码";
    jymiomaLabel.font = [UIFont systemFontOfSize:14];
    [self.twoView addSubview:jymiomaLabel];
    [jymiomaLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.twoView);
        make.left.equalTo(self.twoView).with.offset(15);
        make.width.equalTo(@60);
    }];
    
    self.yanjingButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.twoView addSubview:self.yanjingButton];
    [self.yanjingButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.twoView);
        make.right.equalTo(self.twoView).with.offset(-15);
        
    }];
    [self.yanjingButton setImage:[UIImage imageNamed:@"icon_biyan_h"] forState:UIControlStateNormal];
    [self.yanjingButton addTarget:self action:@selector(jymimaButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.jymimaTextField = [[UITextField alloc] init];
    self.jymimaTextField.keyboardType=UIKeyboardTypeNumberPad;
    [self.twoView addSubview:self.jymimaTextField];
    [self.jymimaTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.twoView);
        make.left.equalTo(jymiomaLabel.mas_right).with.offset(15);
        make.right.equalTo(self.yanjingButton.mas_left).with.offset(-15);
        
    }];
    self.jymimaTextField.secureTextEntry = YES;
    self.jymimaTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.jymimaTextField.placeholder =@"请输入交易密码";
    self.jymimaTextField.font = [UIFont systemFontOfSize:14.f];
    self.jymimaTextField.delegate = self;
    
    
    UILabel * sjNamberlabel = [[UILabel alloc] init];
    sjNamberlabel.text = @"手机号码";
    sjNamberlabel.textColor = [UIColor grayColor];
    sjNamberlabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:sjNamberlabel];
    [sjNamberlabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).with.offset(15);
        make.top.equalTo(self.twoView.mas_bottom).with.offset(18);
    }];
    
    self.sjNbrtextlabel = [[UILabel alloc] init];
    self.sjNbrtextlabel.textColor = [UIColor grayColor];
    self.sjNbrtextlabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:self.sjNbrtextlabel];
    [self.sjNbrtextlabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(sjNamberlabel.mas_right).with.offset(16);
        make.top.equalTo(self.twoView.mas_bottom).with.offset(18);
    }];
    
    self.sjNbrtextlabel.text = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"phoneNumber"]];
    
    
    UILabel * yanzhengmaLabel = [[UILabel alloc] init];
    yanzhengmaLabel.text = @"验证码";
    yanzhengmaLabel.font = [UIFont systemFontOfSize:14];
    [self.threeView addSubview:yanzhengmaLabel];
    [yanzhengmaLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.threeView);
        make.left.equalTo(self.threeView).with.offset(15);
        make.width.equalTo(@60);
    }];
    
    self.yanzhengmaButton = [EBCountDownButton buttonWithType:UIButtonTypeCustom];
    [self.threeView addSubview:self.yanzhengmaButton];
    [self.yanzhengmaButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.threeView);
        make.right.equalTo(self.threeView).with.offset(-15);
        make.width.equalTo(@80);
        
    }];
    [self.yanzhengmaButton setTitle:@"发送验证码" forState:UIControlStateNormal];
    [self.yanzhengmaButton setTitleColor:[UIColor blueColor]forState:UIControlStateNormal];
    self.yanzhengmaButton.titleLabel.font = [UIFont systemFontOfSize: 15.0];
    [self.yanzhengmaButton addTarget:self action:@selector(yanzhengmaButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.yanzhengmaTextField = [[UITextField alloc] init];
    self.yanzhengmaTextField.keyboardType=UIKeyboardTypeNumberPad;
    [self.threeView addSubview:self.yanzhengmaTextField];
    [self.yanzhengmaTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.threeView);
        make.left.equalTo(yanzhengmaLabel.mas_right).with.offset(15);
        make.right.equalTo(self.yanzhengmaButton.mas_left).with.offset(-15);
        
    }];
    self.yanzhengmaTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.yanzhengmaTextField.placeholder =@"请输入手机验证码";
    self.yanzhengmaTextField.font = [UIFont systemFontOfSize:14.f];
    self.yanzhengmaTextField.delegate = self;
    
    self.querenButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:self.querenButton];
    [self.querenButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.threeView.mas_bottom).with.offset(60);
        make.centerX.equalTo(self.view);
        
    }];
    [self.querenButton setBackgroundImage:[UIImage imageNamed:@"icon_anniu_f"] forState:UIControlStateNormal];
    self.querenButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.querenButton setTitle:@"确认" forState:UIControlStateNormal];
    
    [self.querenButton addTarget:self action:@selector(querenButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    
}


//眼睛按钮
- (void)jymimaButtonAction:(UIButton *)sender {
    
    if (self.jymimaTextField.secureTextEntry == YES) {
        
        self.jymimaTextField.secureTextEntry = NO;
        [self.yanjingButton setImage:[UIImage imageNamed:@"icon_yangjingh"] forState:UIControlStateNormal];
    }else {
        self.jymimaTextField.secureTextEntry = YES;
        [self.yanjingButton setImage:[UIImage imageNamed:@"icon_biyan_h"] forState:UIControlStateNormal];
        
    }
}

//获取验证码
- (void)yanzhengmaButtonAction:(UIButton *)sender {
    
    [self.yanzhengmaButton countDownWithDuration:180 completion:^(BOOL finished) {
        NSLog(@"finished");
    }];
    NSDictionary * para = @{@"phone" : self.sjNbrtextlabel.text,
                             @"type" : @(7)
                             };
    
    [GPosAPI requestSendCodeWithParams:para andCallback:^(id obj) {
        NSLog(@"--%@",obj);
        
        if ( obj == nil )
        {
            
            self.hud=[WKProgressHUD popMessage:@"请求失败" inView:self.view duration:1 animated:YES];
            
        }else{
            
            if ([[obj objectForKey:@"code"] intValue] == 200) {
                self.hud=[WKProgressHUD popMessage:@"发送短信验证码成功" inView:self.view duration:1 animated:YES];
                
                
            }else if ([[obj objectForKey:@"code"] intValue] == 401 || [[obj objectForKey:@"code"] intValue] == 402){
                
                UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"passWord"];
                //storyboard里的ID
                XMRegisterViewController *vc = [mainStory instantiateInitialViewController];
                vc.navigationController.navigationBarHidden=NO;
                //                    //设置当前窗口的根控制器
                [UIApplication sharedApplication].keyWindow.rootViewController=vc;
                
                [SVProgressHUD showInfoWithStatus:[obj objectForKey:@"message"]];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                
            }else{
                
                self.hud=[WKProgressHUD popMessage:[obj objectForKey:@"message"] inView:self.view duration:1 animated:YES];
                
                
            }
            
            
        }
        
        
    }];
    
    
}

//确认按钮的方法
- (void)querenButtonAction:(UIButton *)sender {

    if (self.shuliangTextField.text.length == 0) {
        self.hud=[WKProgressHUD popMessage:@"GPOS数量不能为空" inView:self.view duration:1 animated:YES];
        return;
    }
    
    if (self.jymimaTextField.text.length == 0) {
        self.hud=[WKProgressHUD popMessage:@"交易密码不能为空" inView:self.view duration:1 animated:YES];
        return;
    }
    
    if (self.yanzhengmaTextField.text.length == 0) {
        self.hud=[WKProgressHUD popMessage:@"验证码不能为空" inView:self.view duration:1 animated:YES];
        return;
    }
    
    
    if (self.jymimaTextField.text.length != 6) {
        self.hud=[WKProgressHUD popMessage:@"交易密码长度必须为6个字符" inView:self.view duration:1 animated:YES];
        return;
    }
    
    if (self.yanzhengmaTextField.text.length != 6) {
        self.hud=[WKProgressHUD popMessage:@"验证码不正确" inView:self.view duration:1 animated:YES];
        return;
    }
    
    int user = [[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"] intValue];
    NSString * openid = [[NSUserDefaults standardUserDefaults] objectForKey:@"openId"];
    NSDictionary * params = @{@"userId" : @(user),
                              @"amount" : self.shuliangTextField.text,
                              @"password" : self.jymimaTextField.text,
                              @"verifyCode" : self.yanzhengmaTextField.text,
                              @"openId" : openid
                              };
    NSLog(@"para---%@",params);
    self.querenButton.userInteractionEnabled=NO;
    [GPosAPI requestDivertZZWithParams:params andCallback:^(id obj) {

        if ( obj == nil )
        {

            self.hud=[WKProgressHUD popMessage:@"请求失败" inView:self.view duration:1 animated:YES];
            self.querenButton.userInteractionEnabled=YES;

        }else{

            if ([[obj objectForKey:@"code"] intValue] == 200) {
                [SVProgressHUD showSuccessWithStatus:@"发送成功"];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];
                
                
                NSNotification *LoseResponse = [NSNotification notificationWithName:@"buttonLoseRespon" object:nil];
                
                //                    2.发送通知:
                [[NSNotificationCenter defaultCenter] postNotification:LoseResponse];
                
                for (UIViewController *temp in self.navigationController.viewControllers)
                {
                    if ([temp isKindOfClass:[XMHomeViewController class]]) {[self.navigationController popToViewController:temp animated:YES];
                    
                }
            }
                    

                self.querenButton.userInteractionEnabled=YES;
            }else if ([[obj objectForKey:@"code"] intValue] == 401 || [[obj objectForKey:@"code"] intValue] == 402) {
                UIStoryboard *mainStory = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"passWord"];
                //storyboard里的ID
                XMRegisterViewController *vc = [mainStory instantiateInitialViewController];
                vc.navigationController.navigationBarHidden=NO;
                //                    //设置当前窗口的根控制器
                [UIApplication sharedApplication].keyWindow.rootViewController=vc;
                self.querenButton.userInteractionEnabled=YES;
                [SVProgressHUD showInfoWithStatus:[obj objectForKey:@"message"]];
                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
                [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeFlat];



            }else {
                self.querenButton.userInteractionEnabled=YES;
                self.hud=[WKProgressHUD popMessage:[obj objectForKey:@"message"] inView:self.view duration:1 animated:YES];

            }


        }



    }];
    
}


//键盘设置
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField == self.jymimaTextField ) {
        //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
        if (range.length == 1 && string.length == 0) {
            return YES;
        }
        else if (self.jymimaTextField.text.length >= 6) {
            self.jymimaTextField.text = [textField.text substringToIndex:6];
            
            return NO;
        }
        //设置密文切换时保持之前的输入内容
        NSString *allstr=[textField.text stringByReplacingCharactersInRange:range withString:string];
        if (self.jymimaTextField.isSecureTextEntry ==YES)
        {
            self.jymimaTextField.text=allstr;
            return NO;
        }
    }
    
    if (textField == self.yanzhengmaTextField ) {
        //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
        if (range.length == 1 && string.length == 0) {
            return YES;
        }
        else if (self.yanzhengmaTextField.text.length >= 6) {
            self.yanzhengmaTextField.text = [textField.text substringToIndex:6];
            
            return NO;
        }
        //设置密文切换时保持之前的输入内容
        NSString *allstr=[textField.text stringByReplacingCharactersInRange:range withString:string];
        if (self.yanzhengmaTextField.isSecureTextEntry ==YES)
        {
            self.yanzhengmaTextField.text=allstr;
            return NO;
        }
//        控制只能输入数字
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUM] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        return [string isEqualToString:filtered];
    }
    
    if (textField == self.shuliangTextField ) {
        //这里的if时候为了获取删除操作,如果没有次if会造成当达到字数限制后删除键也不能使用的后果.
        if (range.length == 1 && string.length == 0) {
            return YES;
        }
        else if (self.shuliangTextField.text.length >= 10) {
            self.shuliangTextField.text = [textField.text substringToIndex:10];
            
            return NO;
        }
        //设置密文切换时保持之前的输入内容
        if ([string isEqualToString:@"."] && ([textField.text rangeOfString:@"."].location != NSNotFound || [textField.text isEqualToString:@""])) {
            return NO;
        }

        NSMutableString *str = [[NSMutableString alloc] initWithString:textField.text];
        [str insertString:string atIndex:range.location];
        if (str.length >= [str rangeOfString:@"."].location+6){
            return NO;
        }
        //
        
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUM] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        return [string isEqualToString:filtered];
        
        
        
    }
    
    return YES;
}


@end
